<template>
  <div class="i-quill" :class="classes">
    <div ref="editor" :style="styles"></div>
    <form enctype="multipart/form-data" id="imgFrom">
      <!-- this.files[0] 图片列表的第0项，也就是当前选择的图片 -->
      <input
        name="imgData"
        type="file"
        multiple
        @change="onFileChange($event)"
        id="imgData"
        style="display: none"
      />
    </form>
  </div>
</template>

<script>
import Quill from 'quill';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import request from '@/plugins/request';
import { titleConfig } from './constants/config';
export default {
  name: 'i-quill',
  props: {
    value: {
      type: String,
      default: ''
    },
    border: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number
    },
    minHeight: {
      type: Number
    },
    toolbar: {
      type: Array | Boolean,
      default: () => [
        ['bold', 'italic', 'underline', 'strike'],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ color: [] }, { background: [] }],
        ['blockquote', 'code-block'],
        [{ list: 'ordered' }, { list: 'bullet' }],
        // [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ align: [] }],
        [{ direction: 'rtl' }],
        // [{ 'font': [] }],
        ['clean'],
        ['link', 'image']
      ]
    },
    readOnly: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      Quill: null,
      currentValue: '',
      options: {
        theme: 'snow',
        bounds: document.body,
        debug: 'warn',
        modules: {
          toolbar: this.toolbar
        },
        placeholder: '内容...',
        readOnly: this.readOnly
      }
    };
  },
  computed: {
    classes () {
      return [
        {
          'i-quill-no-border': !this.border
        }
      ];
    },
    styles () {
      let style = {};
      // if (this.minHeight) {
      //     style.minHeight = `${this.minHeight}px`;
      // }
      // if (this.height) {
      //     style.height = `${this.height}px`;
      // }
      style.height = `${800}px`;
      return style;
    }
  },
  watch: {
    value: {
      handler (val) {
        if (val !== this.currentValue) {
          this.currentValue = val;
          if (this.Quill) {
            this.Quill.pasteHTML(this.value);
          }
        }
      },
      immediate: true
    }
  },
  mounted () {
    this.init();
    this.initTitle();
  },
  methods: {
    handleCustomPaste (e) {
      if (!e.clipboardData.getData('Text')) {
        this.$message.warning('不支持图片粘贴,请使用图片上传功能添加图片')
        e.preventDefault()
      }
    },
    initTitle () {
      document.getElementsByClassName('ql-editor')[0].dataset.placeholder = ''
      for (let item of titleConfig) {
        let tip = document.querySelector('.i-quill ' + item.Choice)
        if (!tip) continue
        tip.setAttribute('title', item.title)
      }
    },
    init () {
      const editor = this.$refs.editor;
      // 初始化编辑器
      this.Quill = new Quill(editor, this.options);
      // 默认值
      this.Quill.pasteHTML(this.currentValue);
      // 绑定事件
      this.Quill.on('text-change', (delta, oldDelta, source) => {
        const html = this.$refs.editor.children[0].innerHTML;
        const text = this.Quill.getText();
        const quill = this.Quill;
        // 更新内部的值
        this.currentValue = html;
        // 发出事件 v-model
        this.$emit('input', html);
        // 发出事件
        this.$emit('on-change', { html, text, quill });
      });
      // 将一些 quill 自带的事件传递出去
      this.Quill.on('text-change', (delta, oldDelta, source) => {
        this.$emit('on-text-change', delta, oldDelta, source);
      });
      this.Quill.on('selection-change', (range, oldRange, source) => {
        this.$emit('on-selection-change', range, oldRange, source);
      });
      this.Quill.on('editor-change', (eventName, ...args) => {
        this.$emit('on-editor-change', eventName, ...args);
      });
      let toolbar = this.Quill.getModule('toolbar');
      toolbar && toolbar.addHandler('image', () => {
        document.getElementById('imgData').click();
      });
      this.$refs.editor.addEventListener('paste', this.handleCustomPaste)
    },
    updateImg (e) {
      console.log(e)
      let param = new FormData(); // 创建form对象
      param.append('myfile', e.target.files[0]);
      request({
        url: this.uploadBaseURL + 'sysback/fileserver/upload',
        method: 'post',
        data: param,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.retStatus === '1') {
          const range = this.Quill.getSelection();
          if (range) {
            this.Quill.insertEmbed(
              range.index,
              'image',
              this.imgBaseURL + res.retData
            ); // 将上传好的图片，插入到富文本的range.index（当前光标处）
          }
        }
      });
    },
    onFileChange (e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      let leng = files.length;
      let requestList = [];
      for (let i = 0; i < leng; i++) {
        requestList.push(this.uploadImgAction(files[i]));
      }
      Promise.all(requestList)
        .then((resList) => {
          let revertList = resList.reverse()
          const range = this.Quill.getSelection();
          let imgListLength = revertList.length;
          if (range) {
            for (let k = 0; k < imgListLength; k++) {
              this.Quill.insertEmbed(
                range.index,
                'image',
                this.getImgUrlFn(revertList[k].retData)
              );
            }
          }
        });
    },
    uploadImgAction (file) {
      let param = new FormData(); // 创建form对象
      param.append('myfile', file);
      return request({
        url: this.uploadBaseURL + 'sysback/fileserver/upload',
        method: 'post',
        data: param,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    },
    createImage (file) {
      let param = new FormData(); // 创建form对象
      param.append('myfile', file);
      request({
        url: this.uploadBaseURL + 'sysback/fileserver/upload',
        method: 'post',
        data: param,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        if (res.retStatus === '1') {
          const range = this.Quill.getSelection();
          if (range) {
            // this.Quill.insertEmbed(range.index, 'image', this.imgBaseURL + res.retData); // 将上传好的图片，插入到富文本的range.index（当前光标处）
            this.Quill.insertEmbed(
              range.index,
              'image',
              this.getImgUrlFn(res.retData)
            );
          }
        }
      });
    },
    /* 获取图片路径 */
    getImgUrlFn (url) {
      let start = 'https://fsyuncai.oss-cn-beijing.aliyuncs.com';
      // let end = '?x-oss-process=style/marking_text';
      let end = '?x-oss-process=style/marking_detail';
      let result = url.indexOf(start) == -1 ? start + url + end : url;
      return result;
    }
  },
  beforeDestroy () {
    // 在组件销毁后销毁实例
    this.Quill = null;
  }
};
</script>
<style lang="less">
.i-quill-no-border {
  .ql-toolbar.ql-snow {
    border: none;
    border-bottom: 1px solid #e8eaec;
  }
  .ql-container.ql-snow {
    border: none;
  }
}
.i-quill {
  height: 250px;
}
</style>
